_base_ = ['../../_base_/datasets/mot_challenge.py',
          '../../_base_/models/deformable_detr_r50.py',
          '../../_base_/default_runtime.py']

samples_per_gpu = 3
img_scale = (720, 1280)

model = dict(
    type='ByteTrack',
    detector=dict(
        init_cfg=dict(
            type='Pretrained',
            checkpoint=  # noqa: E251
            '/data1/dn/mmdetection/work_dirs/half-half_One-class_DeformDETR_R50_20e_roadtext_twostage_refine/latest.pth'
            # noqa: E501
        ),
        ),
    motion=dict(type='KalmanFilter'),
    tracker=dict(
        type='ByteTracker',
        obj_score_thrs=dict(high=0.6, low=0.1),
        init_track_thr=0.,   # 0.7,
        weight_iou_with_det_scores=True,
        match_iou_thrs=dict(high=0.1, low=0.5, tentative=0.3),
        num_frames_retain=30)
)

img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Rotate', level=5, max_rotate_angle=20),
    dict(type='Shear', level=5, prob=0.1),
    dict(
        type='AutoAugment',
        policies=[
            [
                dict(
                    type='Resize',
                    img_scale=img_scale,
                    ratio_range=(0.8, 1.2),
                    keep_ratio=True)
            ],
            [
                dict(
                    type='Resize',
                    # The radio of all image in train dataset < 7
                    # follow the original impl
                    img_scale=[(720, 1280), (1440, 2560), (2160, 3840)],
                    multiscale_mode='value',
                    keep_ratio=True),
                dict(
                    type='RandomCrop',
                    crop_type='absolute_range',
                    crop_size=(384, 600),
                    allow_negative_crop=False),
                dict(
                    type='Resize',
                    img_scale=img_scale,
                    ratio_range=(0.8, 1.2),
                    override=True,
                    keep_ratio=True)
            ]
        ]),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size_divisor=32),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])
]
# test_pipeline, NOTE the Pad's size_divisor is different from the default
# setting (size_divisor=32). While there is little effect on the performance
# whether we use the default setting or use size_divisor=1.
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=img_scale,
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(
                type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='VideoCollect', keys=['img'])
        ])
]

# dataset settings
data_root = 'data/MOT_roadtext_eng_only/'
data = dict(
    samples_per_gpu=samples_per_gpu,
    workers_per_gpu=4,
    persistent_workers=True,
    train=dict(
        _delete_=True,
        type='CocoDataset',
        ann_file=data_root + 'annotations/train_cocoformat.json',
        img_prefix=data_root + 'train',
        classes=('pedestrian',),         # 必须加上，因为是基于COCO
        filter_empty_gt=False,
        pipeline=train_pipeline),
    val=dict(
        pipeline=test_pipeline,
        ann_file=data_root + 'annotations/test_perfect_cocoformat.json',
        img_prefix=data_root + 'test',
        interpolate_tracks_cfg=dict(min_num_frames=5, max_num_frames=200)),     # 5, 20会出现错误
    test=dict(
        pipeline=test_pipeline,
        ann_file=data_root + 'annotations/test_perfect_cocoformat.json',
        img_prefix=data_root + 'test',
        interpolate_tracks_cfg=None))   # dict(min_num_frames=5, max_num_frames=200)))

# optimizer
optimizer = dict(
    _delete_=True,
    type='AdamW',
    lr=2e-5 / 32 * samples_per_gpu * 5,  # 原始：2e-4, 并没有使用lr缩放。（因为命令行输入时忘记了）
    weight_decay=0.0001,
    paramwise_cfg=dict(
        custom_keys={
            'backbone': dict(lr_mult=0.1),
            'sampling_offsets': dict(lr_mult=0.1),
            'reference_points': dict(lr_mult=0.1)
        }))
optimizer_config = dict(
    _delete_=True,
    grad_clip=dict(max_norm=0.1, norm_type=2))

# NOTE: `auto_scale_lr` is for automatically scaling LR,
# USER SHOULD NOT CHANGE ITS VALUES.
# base_batch_size = (16 GPUs) x (2 samples per GPU)
auto_scale_lr = dict(base_batch_size=32)
device = 'cuda'

# learning policy
total_epochs = 30
lr_config = dict(policy='step', step=[8, 15])
runner = dict(type='EpochBasedRunner', max_epochs=total_epochs)

checkpoint_config = dict(interval=1)
evaluation = dict(metric=['bbox', 'track'], interval=1)
search_metrics = ['MOTA', 'IDF1', 'FN', 'FP', 'IDs', 'MT', 'ML']

# # you need to set mode='dynamic' if you are using pytorch<=1.5.0
# fp16 = dict(loss_scale=dict(init_scale=512.))
